package com.github.elliot.usercenter.service;

import com.github.elliot.usercenter.dao.PermissionRepository;
import com.github.elliot.usercenter.dao.RoleRepository;
import com.github.elliot.usercenter.po.Permission;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class RoleService {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    public Flux<String> getBackendUrlByRoleList(List<String> roleList){
        return roleRepository.getBackendUrlByRoleList(roleList);
    }

    public Flux<Permission> getBackendUrlByUserNo(String userNo) {
        return roleRepository.getRoleListByUserNo(userNo)
                .flatMap(roleNo -> permissionRepository.findPermissionListByRoleNo(roleNo))
                .collectList()
                .flatMapMany(permissionNoList -> permissionRepository.findBackendUrlListByPermissionNo(permissionNoList)
                        .filter(StringUtils::isNoneBlank)
                        .map(backendUrl -> backendUrl.split(","))
                        .map(Arrays::asList)
                        .flatMap(Flux::fromIterable))
                .map(e -> {
                    Permission permission = new Permission();
                    permission.setBackendUrl(e);
                    return permission;
                });
    }
}
